package cluster

import akka.actor.typed.{ActorRef, Behavior}
import akka.actor.typed.receptionist.{Receptionist, ServiceKey}
import akka.actor.typed.scaladsl.Behaviors
import tool.Pojo._
import scala.concurrent.duration._

/**
 * Created by yz on 30/9/2020
 */
object Client {

  def apply(): Behavior[ClientCommand] = {

    Behaviors.setup[ClientCommand] { context =>
      Behaviors.withTimers { timers =>
        timers.startTimerAtFixedRate(Tick, 2.seconds)
        boot()
      }


    }
  }

  def boot(): Behavior[ClientCommand] = Behaviors.receive[ClientCommand] { (context, message) =>
    val log = context.log
    message match {
      case MyDbUpdated(MyDb.myDbKey.Listing(listings)) =>
        println(listings)
        listings.foreach { myDb =>
          myDb ! SetRequest("123", new Integer(123), context.self)
          myDb ! GetRequest("123", context.self)
        }
        Behaviors.same
      case Tick =>
        val listingResponseAdapter = context.messageAdapter[Receptionist.Listing] { listing =>
          MyDbUpdated(listing)
        }
        context.system.receptionist ! Receptionist.Subscribe(MyDb.myDbKey, listingResponseAdapter)
        Behaviors.same
      case LogTest(message) =>
        log.info(message)
        Behaviors.same
      case Value(value) =>
        log.info(s"get value ${value}")
        Behaviors.same
    }
  }


}
